'use client';

import { useState, useEffect } from 'react';

interface ImportExportToolbarProps {
  onExportSelected: (format: 'csv' | 'xls' | 'xlsx') => void;
  onExportAll: (format: 'csv' | 'xls' | 'xlsx') => void;
  onImport: (file: File, format: 'csv' | 'xls' | 'xlsx') => Promise<void>;
  onDownloadTemplate: (format: 'csv' | 'xls' | 'xlsx') => void;
  isImporting?: boolean;
  selectedCount: number;
  totalCount: number;
  disabled?: boolean;
}

export default function ImportExportToolbar({
  onExportSelected,
  onExportAll,
  onImport,
  onDownloadTemplate,
  isImporting = false,
  selectedCount,
  totalCount,
  disabled = false,
}: ImportExportToolbarProps) {
  const [showExportMenu, setShowExportMenu] = useState(false);
  const [showImportMenu, setShowImportMenu] = useState(false);
  const [showTemplateMenu, setShowTemplateMenu] = useState(false);

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      const target = e.target as HTMLElement;
      if (!target.closest('[data-menu-container]')) {
        setShowExportMenu(false);
        setShowImportMenu(false);
        setShowTemplateMenu(false);
      }
    };
    if (showExportMenu || showImportMenu || showTemplateMenu) {
      document.addEventListener('click', handleClickOutside);
      return () => document.removeEventListener('click', handleClickOutside);
    }
  }, [showExportMenu, showImportMenu, showTemplateMenu]);

  const handleFileSelect = async (file: File, format: 'csv' | 'xls' | 'xlsx') => {
    setShowImportMenu(false);
    await onImport(file, format);
  };

  return (
    <div style={{ display: 'flex', gap: '10px', alignItems: 'center', flexWrap: 'wrap' }}>
      <div style={{ position: 'relative', display: 'inline-block' }} data-menu-container>
        <button
          className="btn"
          onClick={(e) => {
            e.stopPropagation();
            setShowExportMenu(!showExportMenu);
            setShowImportMenu(false);
            setShowTemplateMenu(false);
          }}
          disabled={disabled}
        >
          导出 {showExportMenu ? '▼' : '▶'}
        </button>
        {showExportMenu && (
          <div
            style={{
              position: 'absolute',
              top: '100%',
              left: 0,
              backgroundColor: 'white',
              border: '1px solid #ddd',
              borderRadius: '4px',
              boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
              zIndex: 1000,
              minWidth: '180px',
              marginTop: '4px',
            }}
          >
            <div style={{ padding: '4px' }}>
              <div style={{ padding: '8px', fontWeight: 'bold', borderBottom: '1px solid #eee' }}>导出选中</div>
              <button
                className="btn"
                style={{
                  width: '100%',
                  textAlign: 'left',
                  padding: '8px',
                  border: 'none',
                  background: 'none',
                  cursor: 'pointer',
                }}
                onClick={() => {
                  onExportSelected('csv');
                  setShowExportMenu(false);
                }}
                disabled={selectedCount === 0}
              >
                .csv
              </button>
              <button
                className="btn"
                style={{
                  width: '100%',
                  textAlign: 'left',
                  padding: '8px',
                  border: 'none',
                  background: 'none',
                  cursor: 'pointer',
                }}
                onClick={() => {
                  onExportSelected('xls');
                  setShowExportMenu(false);
                }}
                disabled={selectedCount === 0}
              >
                .xls
              </button>
              <button
                className="btn"
                style={{
                  width: '100%',
                  textAlign: 'left',
                  padding: '8px',
                  border: 'none',
                  background: 'none',
                  cursor: 'pointer',
                }}
                onClick={() => {
                  onExportSelected('xlsx');
                  setShowExportMenu(false);
                }}
                disabled={selectedCount === 0}
              >
                .xlsx
              </button>
            </div>
            <div style={{ padding: '4px', borderTop: '1px solid #eee' }}>
              <div style={{ padding: '8px', fontWeight: 'bold', borderBottom: '1px solid #eee' }}>导出全部</div>
              <button
                className="btn"
                style={{
                  width: '100%',
                  textAlign: 'left',
                  padding: '8px',
                  border: 'none',
                  background: 'none',
                  cursor: 'pointer',
                }}
                onClick={() => {
                  onExportAll('csv');
                  setShowExportMenu(false);
                }}
                disabled={totalCount === 0}
              >
                .csv
              </button>
              <button
                className="btn"
                style={{
                  width: '100%',
                  textAlign: 'left',
                  padding: '8px',
                  border: 'none',
                  background: 'none',
                  cursor: 'pointer',
                }}
                onClick={() => {
                  onExportAll('xls');
                  setShowExportMenu(false);
                }}
                disabled={totalCount === 0}
              >
                .xls
              </button>
              <button
                className="btn"
                style={{
                  width: '100%',
                  textAlign: 'left',
                  padding: '8px',
                  border: 'none',
                  background: 'none',
                  cursor: 'pointer',
                }}
                onClick={() => {
                  onExportAll('xlsx');
                  setShowExportMenu(false);
                }}
                disabled={totalCount === 0}
              >
                .xlsx
              </button>
            </div>
          </div>
        )}
      </div>

      <div style={{ position: 'relative', display: 'inline-block' }} data-menu-container>
        <button
          className="btn"
          disabled={isImporting || disabled}
          onClick={(e) => {
            e.stopPropagation();
            if (isImporting || disabled) return;
            setShowImportMenu(!showImportMenu);
            setShowExportMenu(false);
            setShowTemplateMenu(false);
          }}
        >
          导入 {showImportMenu ? '▼' : '▶'}
        </button>
        {showImportMenu && (
          <div
            style={{
              position: 'absolute',
              top: '100%',
              left: 0,
              backgroundColor: 'white',
              border: '1px solid #ddd',
              borderRadius: '4px',
              boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
              zIndex: 1000,
              minWidth: '150px',
              marginTop: '4px',
            }}
          >
            <label
              style={{
                display: 'block',
                padding: '8px',
                cursor: 'pointer',
                borderBottom: '1px solid #eee',
              }}
            >
              <input
                type="file"
                accept=".csv"
                style={{ display: 'none' }}
                disabled={isImporting}
                onChange={async (e) => {
                  if (isImporting) {
                    e.currentTarget.value = '';
                    return;
                  }
                  const file = e.target.files?.[0];
                  if (file) {
                    await handleFileSelect(file, 'csv');
                  }
                  e.currentTarget.value = '';
                }}
              />
              .csv
            </label>
            <label
              style={{
                display: 'block',
                padding: '8px',
                cursor: 'pointer',
                borderBottom: '1px solid #eee',
              }}
            >
              <input
                type="file"
                accept=".xls"
                style={{ display: 'none' }}
                disabled={isImporting}
                onChange={async (e) => {
                  if (isImporting) {
                    e.currentTarget.value = '';
                    return;
                  }
                  const file = e.target.files?.[0];
                  if (file) {
                    await handleFileSelect(file, 'xls');
                  }
                  e.currentTarget.value = '';
                }}
              />
              .xls
            </label>
            <label
              style={{
                display: 'block',
                padding: '8px',
                cursor: 'pointer',
              }}
            >
              <input
                type="file"
                accept=".xlsx"
                style={{ display: 'none' }}
                disabled={isImporting}
                onChange={async (e) => {
                  if (isImporting) {
                    e.currentTarget.value = '';
                    return;
                  }
                  const file = e.target.files?.[0];
                  if (file) {
                    await handleFileSelect(file, 'xlsx');
                  }
                  e.currentTarget.value = '';
                }}
              />
              .xlsx
            </label>
          </div>
        )}
      </div>

      <div style={{ position: 'relative', display: 'inline-block' }} data-menu-container>
        <button
          className="btn"
          onClick={(e) => {
            e.stopPropagation();
            setShowTemplateMenu(!showTemplateMenu);
            setShowExportMenu(false);
            setShowImportMenu(false);
          }}
          disabled={disabled}
        >
          下载模板 {showTemplateMenu ? '▼' : '▶'}
        </button>
        {showTemplateMenu && (
          <div
            style={{
              position: 'absolute',
              top: '100%',
              left: 0,
              backgroundColor: 'white',
              border: '1px solid #ddd',
              borderRadius: '4px',
              boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
              zIndex: 1000,
              minWidth: '150px',
              marginTop: '4px',
            }}
          >
            <button
              className="btn"
              style={{
                width: '100%',
                textAlign: 'left',
                padding: '8px',
                border: 'none',
                background: 'none',
                cursor: 'pointer',
                borderBottom: '1px solid #eee',
              }}
              onClick={() => {
                onDownloadTemplate('csv');
                setShowTemplateMenu(false);
              }}
            >
              .csv
            </button>
            <button
              className="btn"
              style={{
                width: '100%',
                textAlign: 'left',
                padding: '8px',
                border: 'none',
                background: 'none',
                cursor: 'pointer',
                borderBottom: '1px solid #eee',
              }}
              onClick={() => {
                onDownloadTemplate('xls');
                setShowTemplateMenu(false);
              }}
            >
              .xls
            </button>
            <button
              className="btn"
              style={{
                width: '100%',
                textAlign: 'left',
                padding: '8px',
                border: 'none',
                background: 'none',
                cursor: 'pointer',
              }}
              onClick={() => {
                onDownloadTemplate('xlsx');
                setShowTemplateMenu(false);
              }}
            >
              .xlsx
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

